
import weexHttp from "@/_js/https"; ;
const weexFunction = weex.requireModule("WeexFunction");

import modal from "@/_js/modal";
import API from "@/_js/api";
import broadcast from "@/_js/broadcast";

var I18N = {};
I18N.en = {
  "启动成功":"Start successfully",
  "本地未找到 &{1} API, 或该API已过期,无法完成操作":"The local & {1} API was not found, or it has expired and cannot complete the operation",
};
I18N.ja = {
  "启动成功":"起動成功",
  "本地未找到 &{1} API, 或该API已过期,无法完成操作":"本地未找到 &{1} API, 或该API已过期,无法完成操作",
};

I18N.ko = {
  "启动成功":"시작 성공",
  "本地未找到 &{1} API, 或该API已过期,无法完成操作":"本地未找到 &{1} API, 或该API已过期,无法完成操作",
};

var language = weex.config.language;
var msg = I18N[language];
if(!msg){
  msg = {};
}
var T = function(text){
    return msg[text] || text;
};
export default {
  /******************************************* 普通方法*/


  /******************************************* 辅助方法*/
  /** 校验参数
   * 
   * @param {参数} param 
   * @param {参数关键字数组} keys 
   * @param {turn弹出Load} hud
   */
  checkParam(param, keys, hud){
    hud&&modal.showLoad();
    for (let index = 0; index < keys.length; index++) {
      var key = keys[index];
      if (param[key] == null) {
        hud&&modal.hideLoad();
        modal.toast('缺失：'+key);
        return true;
      }
    }
    return false;
  },

  /** 校验API
   * 
   * @param {apiId} apiId 
   * @param {Ap名称} apiName 
   */
  checkApi(apiId, apiName, success=()=>{}, failure=()=>{}){
    
    API.getApi(apiId, 'YES', null, (api)=>{
      if (apiId.length > 0 && api == null) {
        modal.toast(T('本地未找到 &{1} API, 或该API已过期,无法完成操作').replace('&(1)',apiName));        failure&&failure();
        return;
      } else {
        success&&success(api);
      }
    });
  },

  /** 获取Api参数
   * 
   * @param {api} api 
   * @param {Boolean} serverType turn执行服务器  false资产服务器
   * @param {*} success 成功回调
   */
  getApiParam(api, serverType, success=(apiMap)=>{}){
    this.httpPublicKey(api.apiId, serverType, (key)=>{
      API.rsaApi(api, key, (rsa)=>{
        var apiMap = {'isMimic':false, 'apiName':api.apiName, 'apiId':api.apiId, 'api':rsa};
        success(apiMap);
      });
    });
  },

  /** 获取执行参数
   * 
   * @param {参数} param 
   * @param {api参数} apiMap 
   */
  getExecuteConfig(param, apiMap){
    
    //交易对数据
    var pairMap = {};
    if (param.pairMap) {
      pairMap = param.pairMap;
      var pairKeys = ['singal', 'last', 'usdPrice', 'baseCoinUsdPrice' ,'increase'];
      for (let index = 0; index < pairKeys.length; index++) {
        var key = pairKeys[index];
        delete pairMap[key];
      }
      pairMap['exchange'] = pairMap.exchangeName;
    }

    //投入数据
    var investMap = {};
    if (param.investCoin) investMap['investCoin'] = param.investCoin;
    if (param.investCoinnNum) {
      investMap['investCoinnNum'] = param.investCoinnNum;
      investMap['counterCoinAmount'] = '0';
      investMap['baseCoinAmount'] =  param.investCoinnNum;
    }

    //执行配置-交易对、参数数组、开仓阈值、其他设置
    var executeConfig = param.executeConfig;
    var tradePair = executeConfig['tradePairs'][0];
    tradePair.leverRate = param.leverRate;
    tradePair.investType = param.investType;
    tradePair.type = param.contractType;

    tradePair = Object.assign(tradePair, apiMap);
    tradePair = Object.assign(tradePair, pairMap);
    tradePair = Object.assign(tradePair, investMap);
    tradePair = Object.assign(tradePair, param.riskMap);

    //合约多空修改到参数数组里面
    if (param.reserves) {
      for (let index = 0; index < param.reserves.length; index++) {
        var reserve = param.reserves[index];
        if (reserve.name == '多空类型') {
          if (param.investType == 0) {
            reserve.value = 1;
          } else if (param.investType == 1) {
            reserve.value = 0;
          } else {
            reserve.value = param.investType;
          }
          break;
        }
      }
      executeConfig['reserves'] =  param.reserves;
    }

    
    if (param.signal) executeConfig['signal'] = param.signal;
    if (param.setMap) executeConfig = Object.assign(executeConfig, param.setMap);

    return executeConfig;
  },

  /******************************************* http*/
  /** HTTP 获取执行服务器公钥
   * 
   * @param {String} apiId 获取服务器公钥
   * @param {Boolean} serverType turn执行服务器  false资产服务器
   * @param {*} success 成功回调
   */
  httpPublicKey(apiId, serverType, success=(key)=>{}){

    if (apiId == null || apiId.length == 0) {
      success('');
      return;
    }
    
    var param = serverType ? {serverType:'strategy'} : {serverType:'accountServer'};
    weexHttp.post("assetsV2/getPublicKey",param,true,(data)=>{
      
      if(data.status == 200){
        var key = data.data.publicKey;
        success&&success(key);
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },
  
  /** HTTP 合约自定义启动
   * 
   * @param {String} address 服务器地址
   * @param {api} api 
   *  
   * @param {策略Id} strategyId 
   * 
   * @param {投资币} investCoin 
   * @param {投资数量} investCoinnNum 
   * @param {杠杆倍率} leverRate
   *  
   * @param {投资方向：0看空 1 看多} investType 
   * @param {OFFICIAL 官方策略 Buy 购买策略 PRIVATE 私有策略} startType 
   * @param {contract 币本位合约 contract_usdt USDT合约} contractType 
   * 
   * @param {执行配置} executeConfig 
   * @param {交易对} pairMap 
   * 
   * @param {参数对象} reserves 
   * @param {其他设置} setMap 
   * @param {仓位风控} riskMap 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpDefineUp(param, success=()=>{}, failure=()=>{}) {

     var keys = ['address', 'api',
                'strategyId', 
                'investCoin', 'investCoinnNum', 'leverRate',
                'investType', 'startType', 'contractType',
                'executeConfig', 'pairMap',
                'signal', 'reserves', 'setMap', 'riskMap'];
    if (this.checkParam(param, keys, true)) return;
    
    this.getApiParam(param.api, false, (apiMap)=>{
      this.getApiParam(param.api, true, (apiMapRun)=>{

        var executeConfig = this.getExecuteConfig(param, apiMapRun);
        var isMimic = apiMap.apiId.length ? false : true;
        var paramMap = {'address':param.address,
                        'strategyId':param.strategyId, 
                        'startType':param.startType,
                        'isMimic':isMimic,
                        'executeConfig':JSON.stringify(executeConfig),

                        'contractType':param.contractType,
                        'apiId':apiMap.apiId,
                        'apiData':apiMap.api};
        if (param.followConfig != null) paramMap['followConfig'] = param.followConfig;
        if (param.isOpenFollow != null) paramMap['isOpenFollow'] = param.isOpenFollow;
        
        weexHttp.postX("contract/defineStart",paramMap,true,(data)=>{
          modal.hideLoad();
          if(data.status == 200){
            modal.toast(T('启动成功'));
            broadcast.send('UpShow', {'index':1});
            success&&success();
          } else if (data.status == 6074) {
            modal.alert({'message':'API资产已改变，同步资产后重新尝试启动', 'btn':'同步资产'}, ()=>{
              
              modal.showLoad();
              var ok = ()=>{
                setTimeout(() => {
                  modal.hideLoad();
                  failure&&failure();
                }, 3000);
              };
              API.synchroApi(apiMap.apiId, ok(), ok());
            });
          } else {
            modal.toast(data.msg);
            failure&&failure();
          }
        });
      });
    });
  },
}
  